<template>
  <div >
    <el-button type="danger" round style="background-color: #2974FF;" @click="opensx('daoru')" >按入订单创建</el-button>
    <el-button  type="danger" round style="background-color: #2974FF;" @click="opensx('yingxiao')" >创建营销任务</el-button> 
    <el-dialog
      :title='type=="daoru"?"依据导入订单创建任务":"创建营销任务"'
      :visible.sync="isshowpz"
      @closed="hideClick"
      :close-on-click-modal="false"	
      width="1160px"> 
        <div class="t_form_box">
            <div class="t_form_item">
                <div class="t_form_title"><span class="t_red">*</span>任务名称</div>
                <el-input style="width: 193px;" v-model="sendformtask.name"></el-input>
            </div>
            <div class="t_form_item">
                <div class="t_form_title"><span class="t_red">*</span>任务类型</div>
                <el-select v-model="sendformtask.type" placeholder="请选择" >
                  <el-option
                    v-for="(item,index) in taskTypeList"
                    :key="index"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
            </div>
            <div class="t_form_item" >
                <div class="t_form_title">91粉加人任务</div>
                <el-select v-model="sendformtask.is_add_user" placeholder="请选择">
                  <el-option label="否" :value="0"></el-option>
                  <el-option label="是" :value="1"></el-option>
                </el-select>
            </div>
            <div class="t_form_item">
                <div class="t_form_title">关联短信任务</div>
                <el-select multiple v-model="sendformtask.sms_task_id" placeholder="请选择">
                  <el-option :label="item.name" :value="item.id" v-for="item in duanxinlists" :key="item.id"></el-option>
                </el-select>
            </div>
            <div class="t_form_item">
                <div class="t_form_title">紧急程度</div>
                <el-select v-model="sendformtask.urgency" placeholder="请选择">
                  <el-option label="普通" value="0"></el-option>
                  <el-option label="较高" value="1"></el-option>
                  <el-option label="最高" value="2"></el-option>
                </el-select>
            </div>

            <div v-if="type=='daoru'" class="t_form_item">
                <div class="t_form_title"><span class="t_red">*</span>订单数据</div>
                <el-select v-model="sendformtask.is_old" placeholder="请选择数据库">
                    <el-option label="最近的订单（6个月内订单）" value="0"></el-option>
                    <el-option label="历史订单（6个月之前的订单）" value="1"></el-option>
                  </el-select>
            </div>
            
            <div class="t_form_item" style="width:50%">
                <div class="t_form_title">截止时间</div>
                <el-date-picker style="width: 470px; margin-right: 20px;" v-model="sendformtask.delay_at" 
                  clearable value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                  placeholder="选择截止时间">
                </el-date-picker>
            </div>
            <div style="width: 100%;margin-left: 33px;display: flex; align-items: center;margin-top: 10px;">任务创建订单信息预设
              <el-tooltip class="item" effect="dark" content="外呼过程中如果需要客服创建订单可预设该项，该任务创建的订单会有一个默认的所属商品和订单的来源，客服无需重复选择，提高效率。" placement="top">
                <i style="font-size:18px;margin-left: 5px;" class="el-icon-question"></i>
                </el-tooltip>
            </div>
            <div style="border: 1px solid #F3F5F8;border-radius: 20px;box-sizing: border-box;padding: 20px 30px 0px 30px;width: 100%;display: flex;margin-bottom: 30px;margin-top: 10px;margin-left: 33px;">
              <div class="t_form_item">
                  <div class="t_form_title" style="width: auto;">商品编码</div>
                  <el-select v-model="sendformtask.goods_sku"  filterable clearable placeholder="请选择商品编码">
                      <el-option  v-for="item in shangpinlist" :key="item.id" :label="item.title + '---' + item.fetch_code" :value="item.id"></el-option>
                  </el-select>
              </div>
              <div class="t_form_item" style="width:50%">
                  <div class="t_form_title">创建订单来源</div>
                  <el-select v-model="sendformtask.channel_class" clearable filterable placeholder="请选择来源渠道分类" @change="getlaiyuan">
                    <el-option :label="item.channel_name" :value="item.id"  v-for="item in qudaolists" :key="item.id" ></el-option>
                    </el-select>
                    <el-select style="margin-left: 10px;" v-model="sendformtask.source" clearable filterable placeholder="请选择订单来源" v-if="sendformtask.channel_class">
                      <el-option :label="item.source_name" :value="item.id"  v-for="item in qudaolaiyuanlists" :key="item" ></el-option>
                    </el-select>
              </div>
            </div>
            
            <div class="t_form_item" style="width: 100%;">
                <div class="t_form_title" style="align-self: flex-start;"><span class="t_red">*</span>上传数据</div>
                <upload-excel-component style="display: inline-block;margin-right: 10px;background-color: #409EFF;color: white;width: 104px;border-radius: 50px;text-align: center;" @on-selected-file="exportData" :buttonName="btnname" fontcolor="white"></upload-excel-component>
                <el-button v-if="type=='daoru'" type="text" @click="dload3">下载上传表格模板</el-button>
                <el-button v-if="type=='yingxiao'" type="text" @click="dload4">下载上传表格模板</el-button> 
            </div>
            <div class="t_form_item" style="width: 100%;">
                <div class="t_form_title" style="align-self: flex-start;">话术要求</div>
                <div style="width: 1000px;" ref="editor"></div>
            </div>
            <div style="text-align: right;width: 100%;">
                  <el-button type="primary" round @click="quxiao" style="width: 104px;" >取消</el-button>
                  <el-button type="danger" :loading="sendloading" round
                  style="background-color: #2974FF;" @click="sendformtaskform">发布任务</el-button>
            </div>
        </div>
      
    </el-dialog>
    <el-dialog title="导入提示" :visible.sync="error_log" width="400px">
          <el-alert
            :title="error_data"
            type="error"
            show-icon
            :closable="false">
          </el-alert>
        </el-dialog>
  </div>
</template>

<script>
  import axios from "axios";
  import UploadExcelComponent from "@/components/UploadExcel/index3.vue";
  import E from 'wangeditor'
  export default {
    components: {
      
      UploadExcelComponent
    },
    name: 'quanyi',
    data() {
      return {
        shopid:'',
        isshowpz:false,
        sendformtask: {
          name: '',
          type: '',
          excel: [],
          words: '',
          urgency:'1',
          is_old:'',
          source:"",
          channel_class:"",
          is_add_user:0,
          sms_task_id:"",
          delay_at:''
        },
        shangpinlist:"",
        duanxinlists:"",
        radioT: '',
        sendloading: false,
        taskTypeList:[],
        qudaolaiyuanlists:'',
        btnname:"+上传表格",
        error_log: false,
        error_data: '',
        times:[],
        url: '',
        type:''
      }
    },
    created() {
      //店铺权限问题
			this.shopid = JSON.parse(localStorage.getItem('SHOP')).shop_id;
      this.url = window.location.origin+"/91haoka_platform/"
      
      //获取商品编码
      var that = this;
      axios.get('/api/gth/order-pages2',{params:{
        status:100,
        _page:1,
        _page_size:1000
      }})
      .then(response => {
        if (response.data.msg.code == 0) {
          this.shangpinlist = response.data.data.data
        } else {
          this.$message.error(response.data.msg.info);
        }
      })

      //关联短信任务
      axios.get('/api/plan-market/message/getrenwulist?order_status=-999&status=1')
      .then(response => {
        if (response.data.msg.code == 0) {
          this.duanxinlists = response.data.data.data
        } else {
          this.$message.error(response.data.msg.info);
        }
      })
      //获取销售渠道
      axios.get('/api/form/channels?page_size=2000')
      .then(response => {
        if (response.data.msg.code == 0) {
          this.qudaolists = response.data.data.data
        } else {
          this.$message.error(response.data.msg.info);
        }
      })

 
      
      //获取运营商渠道
      this.getlaiyuan()

    },
    methods: {
      getlaiyuan:function(){
        this.sendformtask.source = ''
        axios.get('/api/form/channel/sources?channel_ids='+this.sendformtask.channel_class)
          .then(response => {
            if (response.data.msg.code == 0) {
                this.qudaolaiyuanlists = response.data.data
            } else {
                this.$message.error(response.data.msg.info);
            }
        })
      },
      //获取产品类型
      getproductstype:function(){
          	var that = this
          	axios.get("/api/plan-market/call/config/list/v2")
          	  .then(function(response) {
          		  if(response.data.msg.code == 0){
                  console.log('eee')
                  console.log(response.data.data)
                  that.taskTypeList = response.data.data
          		  }else{
          		  	that.$message.error(response.data.msg.info);
          		  }

          	  })
          },

      opensx(type){
        this.type = type
        //获取产品类型
        this.getproductstype()
        this.restform()
        this.isshowpz = true
        this.btnname = "+上传表格"
        setTimeout(()=>{
          var that = this
          var editor = new E(this.$refs.editor);
          editor.customConfig.menus = [
            'bold',
            'foreColor',
            'fontSize'
          ]
          editor.customConfig.onchange = function (html) {
            that.sendformtask.words = html
          }
          editor.create();
        },1000)
      },
      hideClick() {//这里是解决富文本嵌套问题
        this.$refs.editor.innerHTML = ''
      },
      
      //订单发布
      sendformtaskform(){
        var that = this
        if(this.sendformtask.name==''){
          this.$message.error('请输入任务名称');
          return
        }
        if(this.sendformtask.excel.length == 0){
          that.$message.error('请上传表格');
          return false;
        }
        if(this.sendformtask.type == ''){
          that.$message.error('请选择任务类型');
          return false;
        }
        if(this.type=='daoru'&&this.sendformtask.is_old == ''){
          that.$message.error('请选择订单数据');
          return false;
        }



        that.sendloading = true
        var data = {}
        data.name = this.sendformtask.name
        // data.end_time = this.sendformtask.endtime
        data.type = this.sendformtask.type
        data.data = this.sendformtask.excel
        data.demand = this.sendformtask.words
        data.urgency = this.sendformtask.urgency
        data.is_old = this.sendformtask.is_old
        data.call_source = this.sendformtask.source
        data.channel_class = this.sendformtask.channel_class
        data.call_goods_sku = this.sendformtask.goods_sku
        data.is_add_user = this.sendformtask.is_add_user
        data.sms_task_id = this.sendformtask.sms_task_id.toString()
        data.delay_at = this.sendformtask.delay_at

        if(this.type == 'yingxiao'){ 
          data.task_type = 3
        }

        axios.post("/api/plan-market/call/task/order_task_create/v2", data)
          .then((response)=> {
              that.sendloading = false
              

              if (response.data.msg.code == 0) {
                  that.isshowpz = false
                  that.sendformtask.excel = []
                  that.$emit('daoruup')
                  
                  that.error_data = response.data.data.message
                  if(that.error_data){
                    that.error_log = true

                  }
              }else{
                  that.$message.error(response.data.msg.info);
              }
        })
      },
      //重置
      restform(){
          this.sendformtask.name= ''
          this.sendformtask.type= ''
          this.sendformtask.excel=[]
          this.sendformtask.words=""
          this.sendformtask.urgency="1"
          this.sendformtask.source= ''
          this.sendformtask.channel_class=''
          this.sendformtask.is_add_user= 0
          this.sendformtask.sms_task_id= ''
          this.sendformtask.delay_at= ''
      },
      //导入
      exportData(data) {
        // this.uploading = false
        // this.shoplog = true
        var that = this;
        let list = [];
        if(data.header[1]=='*联系电话*'){
        //导入excel
        for (var i = 0; i < data.results.length; i++) {
            var obj = {};
            // console.log(data.results[i]["*业务ID*"])
            if(data.results[i]["*业务ID*"] == undefined){
              this.$message.error('解析失败，请仔细检查必填项是否有空值！');
              return
            }
            if(data.results[i]["*业务ID*"] != undefined){
                obj["mission_id"] = data.results[i]["*业务ID*"]
            }

            if(data.results[i]["*联系电话*"] != undefined){
                obj["mobile"] = parseInt(data.results[i]["*联系电话*"])
            }else{
              obj["mobile"] = ''
            }
            if(data.results[i]["外呼执行人"] != undefined){
                obj["caller_name"] = data.results[i]["外呼执行人"];
            }else{
              obj["caller_name"] = '';
            }
            if(data.results[i]["用户姓名"] != undefined){
                obj["user_name"] = data.results[i]["用户姓名"];
            }else{
              obj["user_name"] = '';
            }
            if(data.results[i]["用户信息"] != undefined){
              obj["user_info"] = data.results[i]["用户信息"];
            }else{
              obj["user_info"] = '';
            }
            if(data.results[i]["产品名"] != undefined){
              obj["product"] = data.results[i]["产品名"];
            }else{
              obj["product"] = '';
            }
            if(data.results[i]["地址"] != undefined){
              obj["address"] = data.results[i]["地址"];
            }else{
              obj["address"] = '';
            }
            if(data.results[i]["备注1"] != undefined){
              obj["remark_one"] = data.results[i]["备注1"];
            }else{
              obj["remark_one"] = '';
            }
            if(data.results[i]["备注2"] != undefined){
              obj["remark_two"] = data.results[i]["备注2"];
            }else{
              obj["remark_two"] = '';
            }
            if(data.results[i]["备注3"] != undefined){
              obj["remark_three"] = data.results[i]["备注3"];
            }else{
              obj["remark_three"] = '';
            }
            // console.log(obj)
            list.push(obj);
        }
        this.sendform.excel = list
        this.$message.success('表格上传成功！');
        this.btnname = '更新表格'
        // this.uploading = true

        }

        if(data.header[1]=='*目标达成*'){
          //导入结果
          for (var i = 0; i < data.results.length; i++) {
              var obj = {};
              if(data.results[i]["*业务ID*"] == undefined || data.results[i]["*目标达成*"] == undefined){
                this.$message.error('解析失败，请仔细检查必填项是否有空值！');
                return
              }
              if(data.results[i]["*业务ID*"] != undefined){
                  obj["mission_id"] = data.results[i]["*业务ID*"]
              }
              if(data.results[i]["*目标达成*"] != undefined){
                  obj["ok"] = data.results[i]["*目标达成*"];
              }
              // console.log(obj)
              list.push(obj);
          }
          axios.post("/api/plan-market/task/result/import/v2", {id: this.id,data: list})
              .then(function(response) {
              if (response.data.msg.code == 0) {
                  that.$message.success('导入成功！');
              }else{
                  that.$message.error(response.data.msg.info);
              }
          })
        }

        if(data.header[1]!='*联系电话*' && data.header[1]!='*目标达成*' && data.header[1]!='身份证码'){
        //导入excel
        for (var i = 0; i < data.results.length; i++) {
            var obj = {};
            // if(data.results[i]["订单ID"] == undefined && data.results[i]["外部订单号"] == undefined) {
            //   this.$message.error('解析失败，请仔细检查必填项是否有空值！');
            //   return
            // }
            if(data.results[i]["订单ID"] != undefined){
                obj["order_ids"] = data.results[i]["订单ID"]
            }else{
              obj["order_ids"] = ''
            }

            if(data.results[i]["外部订单号"] != undefined){
                obj["source_ids"] = data.results[i]["外部订单号"]
            }else{
              obj["source_ids"] = ''
            }

            list.push(obj);
        }
        this.sendformtask.excel = list
        this.$message.success('表格上传成功！');
        this.btnname = '更新表格'

        }

        if(data.header[1]=='身份证码'){
          //导入结果
          for (var i = 0; i < data.results.length; i++) {
              var obj = {};
              // if(data.results[i]["*业务ID*"] == undefined || data.results[i]["*目标达成*"] == undefined){
              //   this.$message.error('解析失败，请仔细检查必填项是否有空值！');
              //   return
              // }
              // if(data.results[i]["*业务ID*"] != undefined){
              //     obj["mission_id"] = data.results[i]["*业务ID*"]
              // }
              // if(data.results[i]["*目标达成*"] != undefined){
              //     obj["ok"] = data.results[i]["*目标达成*"];
              // }


              if(data.results[i]["生产号码"] != undefined){
                obj["plan_mobile_produced"] = data.results[i]["生产号码"]
              }else{
                obj["plan_mobile_produced"] = ''
              }

              if(data.results[i]["身份证码"] != undefined){
                obj["id_card_num"] = data.results[i]["身份证码"]
              }else{
                obj["id_card_num"] = ''
              }

              if(data.results[i]["身份证姓名"] != undefined){
                obj["id_card_name"] = data.results[i]["身份证姓名"]
              }else{
                obj["id_card_name"] = ''
              }

              if(data.results[i]["地址"] != undefined){
                obj["address"] = data.results[i]["地址"]
              }else{
                obj["address"] = ''
              }

              if(data.results[i]["联系电话"] != undefined){
                obj["mobile"] = data.results[i]["联系电话"]
              }else{
                obj["mobile"] = ''
              }

              if(data.results[i]["备注1"] != undefined){
                obj["memo1"] = data.results[i]["备注1"]
              }else{
                obj["memo1"] = ''
              }

              if(data.results[i]["备注2"] != undefined){
                obj["memo2"] = data.results[i]["备注2"]
              }else{
                obj["memo2"] = ''
              }

              if(data.results[i]["备注3"] != undefined){
                obj["memo3"] = data.results[i]["备注3"]
              }else{
                obj["memo3"] = ''
              }
              
              
              
              
              
              // console.log(obj)
              list.push(obj);
          }
          this.sendformtask.excel = list
          this.$message.success('表格上传成功！');
          this.btnname = '更新表格'
        }
    },
      dload3:function(){
        const a = document.createElement('a');
        a.setAttribute('download', '上传表格模板.xlsx');
        a.setAttribute('href', this.url+'static/uploadOrderCreatedTask.xlsx');
        a.click();
      },
      dload4:function(){
        const a = document.createElement('a');
        a.setAttribute('download', '上传表格模板.xlsx');
        a.setAttribute('href', this.url+'static/uploadyingxiao.xlsx'); 
        a.click();
      },
      quxiao(){
        this.isshowpz = false
      },
      
    },
    beforeDestroy(){
     
    },
    
    
  }
</script>

<style  scoped>
.t_form_item{
  display: flex;
  width: 33.3%;
  align-items: center;
  margin-bottom: 20px;
}
.t_form_title{
  width: 110px;
  text-align: right;
  box-sizing: border-box;
  padding-right: 15px;
}
.t_form_box{
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
} 
.t_red{
  color: #2974FF;
}
/deep/.t_form_box .el-input--suffix .el-input__inner  {
  background-color: #f7f8fa;
  border: none;
}
/deep/.t_form_box .el-range-editor.el-input__inner{
  background-color: #f7f8fa;
  border: none;
}
/deep/.t_form_box .el-date-editor .el-range-input{
  background-color: #f7f8fa;
  border: none;
}
/deep/.t_form_box .el-input__inner{
  background-color: #f7f8fa;
  border: none;
  
}
  
</style>
